package com.mall.struts.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mall.ibatis.bean.EFunction;
import com.mall.ibatis.bean.Function;
import com.mall.ibatis.bean.FunctionMenu;
import com.mall.ibatis.bean.Operator;
import com.mall.ibatis.bean.ReturnMessage;
import com.mall.service.FunctionMenuService;
import com.mall.service.FunctionService;
import com.mall.service.SysParaService;
import com.mall.util.StringUtil;


public class FunctionMenuAction extends Action
{
	private static Log logger = LogFactory.getLog(FunctionMenuAction.class);
	private static final FunctionMenuService functionMenuService =  FunctionMenuService.getInstance();
	private static final FunctionService functionService = FunctionService.getInstance();
	private static final SysParaService sysParaService = SysParaService.getInstance();
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		String method = request.getParameter("type");
		try
		{
			if(method == null)
			{
				return load(mapping, form, request, response);
			}
			else if(method.equals("query"))
			{
				return query(mapping, form, request, response);
			}
			else if(method.equals("list"))
			{
				return list(mapping, form, request, response);
			}
			else if(method.equals("insert"))
			{
				return insert(mapping, form, request, response);
			}
			else if(method.equals("update"))
			{
				return update(mapping, form, request, response);
			}
			else if(method.equals("delete"))
			{
				return delete(mapping, form, request, response);
			}
			else if(method.equals("selectEFunction"))
			{
				return selectEFunction(mapping, form, request, response);
			}
			else if(method.equals("insertEFunction"))
			{
				return insertEFunction(mapping, form, request, response);
			}
			else if(method.equals("donwnLoacDOC"))
			{
				return donwnLoacDOC(mapping, form, request, response);
			}
			else if(method.equals("upLoad"))
			{
				return upLoad(mapping, form, request, response);
			}
			else if(method.equals("deleteEFunction"))
			{
				return deleteEFunction(mapping, form, request, response);
			}
			else if(method.equals("updateEFunction"))
			{
				return updateEFunction(mapping, form, request, response);
			}
			else if(method.equals("selectFunctionName"))
			{
				return selectFunctionName(mapping, form, request, response);
			}
		}
		catch (Exception e)
		{
			// TODO: handle exception
			request.setAttribute("exceptionMsg", e.getMessage());
			logger.error(e);
			return mapping.findForward("exceptionError");
		}
		
		return mapping.findForward("pageNotFoundError");
		
	}
	
	private ActionForward load(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		functionService.methodFilter(request,response);
		return mapping.findForward("loading");
	}
	
	private ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		
		String menuID =request.getParameter("menuID");
		FunctionMenu functionMenu  =new FunctionMenu();
		functionMenu.setMenuID(menuID);
		
		String reponseXML = functionMenuService.selectFunctionMenu(functionMenu).toXML();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;

	}
	
	
	
	private ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String reponseXML = null;
		
		List<FunctionMenu> functionMenuList = functionMenuService.selectAllFunctionMenu();
		
		reponseXML = functionMenuService.getFunctionMenuList(functionMenuList, 1, 1).toXML();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	private ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String menuID =request.getParameter("menuID");
		String menuName =request.getParameter("menuName");
		String menuAction =request.getParameter("menuAction");
		String menuLabel =request.getParameter("menuLabel");
		String menuView =request.getParameter("menuView");
		String isLeaf =request.getParameter("isLeaf");
		Integer menuLevel =StringUtil.toInteger(request.getParameter("menuLevel"));
		String rootID =request.getParameter("rootID");
		String parentID =request.getParameter("parentID");
		Integer displayOrder =StringUtil.toInteger(request.getParameter("displayOrder"));
		String inputValue =request.getParameter("inputValue");
		String inputKey =request.getParameter("inputKey");
		String menuSeq =request.getParameter("menuSeq");
		String useType =request.getParameter("useType");
		
		FunctionMenu functionMenu = new FunctionMenu();
		functionMenu.setMenuID(menuID);
		functionMenu.setMenuName(menuName);
		functionMenu.setMenuAction(menuAction);
		functionMenu.setMenuLabel(menuLabel);
		functionMenu.setMenuView(menuView);
		functionMenu.setIsLeaf(isLeaf);
		functionMenu.setMenuLevel(menuLevel);
		functionMenu.setRootID(rootID);
		functionMenu.setParentID(parentID);
		functionMenu.setDisplayOrder(displayOrder);
		functionMenu.setInputValue(inputValue);
		functionMenu.setInputKey(inputKey);
		functionMenu.setMenuSeq(menuSeq);
		functionMenu.setUseType(useType);
		ReturnMessage returnMessage=null;
		
		try
		{
			menuID = functionMenuService.insertFunctionMenu(functionMenu);
			returnMessage = new ReturnMessage("1",menuID);
		}
		catch (Exception e)
		{
			// TODO: handle exception
			returnMessage = new ReturnMessage("0",e.getMessage());
			logger.error(e);
		}
		
		String reponseXML = returnMessage.toXMLString();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	private ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String menuID =request.getParameter("menuID");
		String menuName =request.getParameter("menuName");
		String menuAction =request.getParameter("menuAction");
		String menuLabel =request.getParameter("menuLabel");
		String menuView =request.getParameter("menuView");
		String isLeaf =request.getParameter("isLeaf");
		Integer menuLevel =StringUtil.toInteger(request.getParameter("menuLevel"));
		String rootID =request.getParameter("rootID");
		String parentID =request.getParameter("parentID");
		Integer displayOrder = StringUtil.toInteger(request.getParameter("displayOrder"));
		String inputValue =request.getParameter("inputValue");
		String inputKey =request.getParameter("inputKey");
		String menuSeq =request.getParameter("menuSeq");
		String useType =request.getParameter("useType");
		
		FunctionMenu functionMenu = new FunctionMenu();
		functionMenu.setMenuID(menuID);
		functionMenu.setMenuName(menuName);
		functionMenu.setMenuAction(menuAction);
		functionMenu.setMenuLabel(menuLabel);
		functionMenu.setMenuView(menuView);
		functionMenu.setIsLeaf(isLeaf);
		functionMenu.setMenuLevel(menuLevel);
		functionMenu.setRootID(rootID);
		functionMenu.setParentID(parentID);
		functionMenu.setDisplayOrder(displayOrder);
		functionMenu.setInputValue(inputValue);
		functionMenu.setInputKey(inputKey);
		functionMenu.setMenuSeq(menuSeq);
		functionMenu.setUseType(useType);
		ReturnMessage returnMessage=null;
		
		try
		{
			functionMenuService.updateFunctionMenu(functionMenu);
			returnMessage = new ReturnMessage("1","");
		}
		catch (Exception e)
		{
			// TODO: handle exception
			returnMessage = new ReturnMessage("0",e.getMessage());
			logger.error(e);
		}
		
		String reponseXML = returnMessage.toXMLString();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	private ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String menuID =request.getParameter("menuID");
		FunctionMenu functionMenu  =new FunctionMenu();
		functionMenu.setMenuID(menuID);
		ReturnMessage returnMessage=null;
		
		try
		{
			functionMenuService.deleteFunctionMenu(functionMenu);
			returnMessage = new ReturnMessage("1","");
		}
		catch (Exception e)
		{
			// TODO: handle exception
			returnMessage = new ReturnMessage("0",e.getMessage());
			logger.error(e);
		}
		
		String reponseXML = returnMessage.toXMLString();
		
//		System.out.println(reponseXML);
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(reponseXML);
		out.flush();
		out.close();
		return null;
	}
	
	private ActionForward selectEFunction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String functionID = request.getParameter("functionID");
//		System.out.println("测试查询-------------------------"+functionID);
		//得到操作人员信息
		HttpSession session = request.getSession();
		Operator operator = (Operator)session.getAttribute("operator");
		//得到当前系统日期
		String currentDate = sysParaService.selectCurrentDate();
		//传到页面
		request.setAttribute("operator", operator);
		request.setAttribute("currentDate", currentDate);
		
		EFunction eFunction = new EFunction();
		eFunction.setFunctionID(functionID);
		eFunction = functionMenuService.selectEFunction(eFunction);
		
//		String str1= new String(eFunction.getDemandDOC());
//		System.out.println("读取测试-----------------------"+eFunction.getNewDate());
		int flag = 0; 
		JSONObject obj = new JSONObject();
		if(eFunction!=null){
			flag =1;
			obj.put("flag", flag);
			obj.put("functionID", eFunction.getFunctionID());
			obj.put("creater", eFunction.getCreater());
			obj.put("creatDate", eFunction.getCreateDate());
			obj.put("newDate",eFunction.getNewDate());
			obj.put("describe", eFunction.getDescribe());
			obj.put("demandDOC", "");
			obj.put("detialDOC", "");
			obj.put("testDOC", "");
			obj.put("demandName", eFunction.getDemandName());
			obj.put("detialName", eFunction.getDetialName());
			obj.put("testName", eFunction.getTestName());
		}else{
			obj.put("flag", flag);
			obj.put("functionID", functionID);
			obj.put("creater", operator.getOpName());
			obj.put("creatDate", currentDate);
			obj.put("newDate","");
			obj.put("describe", "");
			obj.put("demandDOC", "");
			obj.put("detialDOC", "");
			obj.put("testDOC", "");
			obj.put("demandName", "");
			obj.put("detialName", "");
			obj.put("testName", "");
		}

		response.setContentType("text/json;charset=utf-8");
		response.setCharacterEncoding("utf-8");		
		response.getWriter().print(obj.toString());		
		response.getWriter().close();
		return null;
	}
	
	private ActionForward insertEFunction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		//得到当前用户
		Operator operator = (Operator) request.getSession().getAttribute("operator");
		String functionID = request.getParameter("functionID");
		
		String creater = operator.getOpID();
		String creatDate = request.getParameter("creatDate");
		String describe = request.getParameter("describe");
		String demand = request.getParameter("demand");   //文件路径
		String detial = request.getParameter("detial");   
		String test = request.getParameter("test");
		
//		System.out.println("--------原始路径demand-------------"+demand);
//		System.out.println("--------原始路径test-------------"+test);
	
		String[] fileName1 = demand.split("\\\\");  //取得文件名
		String[] fileName2 = detial.split("\\\\");
		String[] fileName3 = test.split("\\\\");
		
		String demandName = fileName1[fileName1.length-1];
		String detialName = fileName2[fileName2.length-1];
		String testName = fileName3[fileName3.length-1];
		
		//获得项目路径
		String savePath = request.getSession().getServletContext().getRealPath("/uploadPic");
		//System.out.println("-----------------13323------"+savePath);
		demand = savePath+"\\"+demandName;
		detial = savePath+"\\"+detialName;
		test = savePath+"\\"+testName;
		
		//System.out.println("---------测试--------------"+demand);
		
		EFunction eFunction = new EFunction();
		eFunction.setFunctionID(functionID);
		eFunction.setCreater(creater);
		eFunction.setCreateDate(creatDate);
		eFunction.setDescribe(describe);
		eFunction.setDemandName(demandName);
		eFunction.setDetialName(detialName);
		eFunction.setTestName(testName);
		
	    int flag =functionMenuService.insertEFunction(eFunction,demand,detial,test);
//	    System.out.println("---------------------"+flag);
	    
	    response.setContentType("text/json;charset=utf-8");
		response.setCharacterEncoding("utf-8");		
		response.getWriter().print("{flag:'" + flag + "'}");
		response.getWriter().close();
		return null;
	}
	
	private ActionForward updateEFunction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		//得到当前用户
		Operator operator = (Operator) request.getSession().getAttribute("operator");
		String functionID = request.getParameter("functionID");
		String creater = operator.getOpID();
		String creatDate = request.getParameter("creatDate");
		String describe = request.getParameter("describe");
		String demand = request.getParameter("demand");   //文件路径
		String detial = request.getParameter("detial");   
		String test = request.getParameter("test");
		
		EFunction eFunction = new EFunction();
		eFunction.setFunctionID(functionID);
		eFunction.setCreater(creater);
		eFunction.setCreateDate(creatDate);
		eFunction.setDescribe(describe);
		
		//获得项目路径
		String savePath = request.getSession().getServletContext().getRealPath("/uploadPic");
		//System.out.println("-----------------13323------"+savePath);
	    if(demand.length()!=0){
	    	String[] fileName1 = demand.split("\\\\");  //取得文件名
			String demandName = fileName1[fileName1.length-1];
			eFunction.setDemandName(demandName);
			demand = savePath+"\\"+demandName;
	    }
		
		if(detial.length()!=0){
			String[] fileName2 = detial.split("\\\\");
			String detialName = fileName2[fileName2.length-1];	
			eFunction.setDetialName(detialName);
			detial = savePath+"\\"+detialName;
		}
		
		if(test.length()!=0){
			String[] fileName3 = test.split("\\\\");
			String testName = fileName3[fileName3.length-1];
			eFunction.setTestName(testName);
			test = savePath+"\\"+testName;
		}
		
	    int flag =functionMenuService.updateEFunction(eFunction,demand,detial,test);
//	    System.out.println("---------------------"+flag);
	    
	    response.setContentType("text/json;charset=utf-8");
		response.setCharacterEncoding("utf-8");		
		response.getWriter().print("{flag:'" + flag + "'}");
		response.getWriter().close();
		return null;
	}
	
	private ActionForward donwnLoacDOC(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		//得到下载参数，表明下载是哪个功能的那个文件
		String functionID = request.getParameter("functionID");
		String downFile = request.getParameter("downFile");
		int flag = 0;
		//根据下载文件查找
		EFunction efunction = new EFunction();
		efunction.setFunctionID(functionID);
		efunction = functionMenuService.downLoadDOC(efunction, downFile);
		if(efunction!=null){
			flag = 1;
		}
		Blob blob = null;
		String fileName = null;
		if(downFile.equals("demand")){
			blob = (Blob)efunction.getDemandDOC1();
			fileName = efunction.getDemandName();
		}else if(downFile.equals("detail")){
			blob = (Blob)efunction.getDetialDOC1();
			fileName = efunction.getDetialName();
		}else{
			blob = (Blob)efunction.getTestDOC1();
			fileName = efunction.getTestName();
		}
//		System.out.println("----------------"+fileName);
		//得到项目路径
		String savePath = request.getSession().getServletContext().getRealPath("/uploadPic");
		
		//InputStream ins = blob.getBinaryStream();
		File file = new File(savePath+"\\"+fileName);
//        System.out.println("------file-----------"+file);
        String fileName1=file.getName();
//        System.out.println("------fileName1---------"+fileName1);
        try {
        	InputStream is=new FileInputStream(file);
            OutputStream os=response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(os);
//            System.out.println("111");
            fileName1 = java.net.URLEncoder.encode(fileName1, "UTF-8");// 处理中文文件名的问题
            fileName1 = new String(fileName1.getBytes("UTF-8"), "GBK");// 处理中文文件名的问题
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("Application/x-msdownload");// 不同类型的文件对应不同的MIME类型
            
              
            response.setHeader("Content-Disposition","attachment;filename="+new String(fileName1.getBytes("gb2312"),"iso8859-1"));
            response.setHeader("Content-Length", String.valueOf(bis.available())); 

            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = bis.read(buffer)) != -1){
                bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
            }
//            System.out.println("222");
            bos.flush();
            bos.close();
            bis.close();
            
            os.close();
            is.close();
		} catch (Exception e) {
//			System.out.println("下载出错！");
		}
        
		
//		OutputStream fout = new FileOutputStream(file);
//		byte[] b= new byte[1024];
//		int len = 0;
//		while((len = ins.read(b)) != -1){
//			fout.write(b, 0, len);
//		}
//		fout.close();
//		ins.close();
//		System.out.println(flag);
		response.setContentType("text/json;charset=utf-8");
		response.setCharacterEncoding("utf-8");		
		response.getWriter().print("{flag:" + flag + "'}");
		response.getWriter().close();
//		System.out.println("333");
		return null;
	}
	
	private ActionForward upLoad(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		response.setContentType("text/plain");
	    //同意格式，页面接受和传递都用UTF-8的形式，否则页面显示会出现乱码
	    request.setCharacterEncoding("UTF-8");
	    response.setCharacterEncoding("UTF-8");
		
	    String test = request.getParameter("menuID1");
//	    System.out.println(test);
	    
		File tmpDir = null;
		File saveDir = null;
		String tmpPath = "c:" + "\tmpdir";
		//得到本项目的目录
		String savePath = request.getSession().getServletContext().getRealPath("/uploadPic");
//		System.out.println("-------------"+savePath);
		//String savePath = "F:\\test";
//		System.out.println(savePath);
		tmpDir = new File(tmpPath);
		saveDir = new File(savePath);
		if (!tmpDir.isDirectory()){
			tmpDir.mkdir();
		}
		if (!saveDir.isDirectory()){
			saveDir.mkdir();
		}
		try{
	        if(ServletFileUpload.isMultipartContent(request)){
	          DiskFileItemFactory dff = new DiskFileItemFactory();//创建该对象
	          
	          dff.setRepository(tmpDir);//指定上传文件的临时目录
	          
	          dff.setSizeThreshold(1024000);//指定在内存中缓存数据大小,单位为byte
	          
	          ServletFileUpload sfu = new ServletFileUpload(dff);//创建该对象
	          
	          //sfu.setFileSizeMax(5000000);//指定单个上传文件的最大尺寸
	          sfu.setSizeMax(100000000);//指定一次上传多个文件的总尺寸
	          
	          FileItemIterator fii = sfu.getItemIterator(request);//解析request 请求,并返回FileItemIterator集合
	          while(fii.hasNext()){
	            FileItemStream fis = fii.next();//从集合中获得一个文件流
	            if(!fis.isFormField() && fis.getName().length()>0){//过滤掉表单中非文件域
	            	
	                String fileSufex = fis.getName().substring(fis.getName().lastIndexOf("."));//获得上传文件的后缀
//	                System.out.println(fileSufex+"后缀");
	                String fileName = fis.getName().substring(fis.getName().lastIndexOf("\\"));//获得上传文件的文件名
//	                System.out.println(fileName);
	                BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流
	                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(saveDir+fileName)));//获得文件输出流
	                Streams.copy(in, out, true);//开始把文件写到你指定的上传文件夹
	            }
	          }
	          //response.getWriter().println("File upload successfully!!!");//终于成功了,还不到你的上传文件中看看,你要的东西都到齐了吗
	        }
	    }catch(Exception e){
	        e.printStackTrace();
	    }
	     return  null;
	}
	
	private ActionForward deleteEFunction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
			{
		//得到删除的功能id
		String functionID = request.getParameter("functionID");
//		System.out.println("--------删除测试-----"+functionID);
		//根据下载文件查找
		EFunction efunction = new EFunction();
		efunction.setFunctionID(functionID);
		int flag = functionMenuService.deleteEFunction(efunction);
//		System.out.println("-------"+flag);
		response.setContentType("text/json;charset=utf-8");
		response.setCharacterEncoding("utf-8");		
		response.getWriter().print("{flag:'" + flag + "'}");
		response.getWriter().close();
		return null;
		}
	
	private ActionForward selectFunctionName(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception
			{
			String functionID = request.getParameter("functionId");
			Function function = new Function();
			function.setFunctionID(functionID);
			function = functionMenuService.selectFunctionName(function);
			//定义一个常量数组，判断视频是否存在
			ArrayList<String> finalVar = new ArrayList<String>();
			finalVar.add("000307");
			finalVar.add("000311");
			finalVar.add("000312");
			finalVar.add("000313");
			finalVar.add("000315");
			finalVar.add("000316");
			finalVar.add("000317");
			finalVar.add("000501");
			finalVar.add("000502");
			finalVar.add("000602");
			finalVar.add("000604");
			finalVar.add("000701");
			finalVar.add("000703");
			finalVar.add("000704");
			finalVar.add("00031401");
			finalVar.add("00031402");
			finalVar.add("00031403");
			finalVar.add("00031404");
			//判断当前页面是否存在视频,flag为查找的返回标志
			int flag = 0;
			for(int i = 0;i<finalVar.size();i++){
				if(functionID.equals(finalVar.get(i))){
					flag = 1;
					break;
				}
			}
			response.setContentType("text/json;charset=utf-8");
			response.setCharacterEncoding("utf-8");		
			response.getWriter().print("{name:'" + functionID +"',flag:'"+flag+ "'}");
			response.getWriter().close();
			 
			return null;
		}
	
}